package com.leilbase.mspring.web.handler;

import com.leilbase.mspring.bean.BeanFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.stream.Collectors;

public class MappingHandler {

    private String uri;

    private Method method;

    private Class<?> controller;

    private String[] args;

    public MappingHandler(String uri, Method method, Class<?> controller, String[] args) {
        this.uri = uri;
        this.method = method;
        this.controller = controller;
        this.args = args;
    }

    public boolean handle(ServletRequest request, ServletResponse response) throws IllegalAccessException, InstantiationException, InvocationTargetException, IOException {
        String requestUri = ((HttpServletRequest)request).getRequestURI();
        if (!requestUri.equals(this.uri)) return false;
//        Class<?>[] parameterTypes = this.method.getParameterTypes();
//        Object[] parameters = new Object[this.args.length];
//        for (int i = 0; i < this.args.length; i++) {
//            Object obj = parameterTypes[i].cast(request.getParameter(this.args[i]));
//            parameters[i] = obj;
//        }
        Object[] parameters = Arrays.stream(this.args)
                .map(name -> (Object) (request.getParameter(name)))
                .collect(Collectors.toList()).toArray(new Object[this.args.length]);
        Object controllerInstance = BeanFactory.getBean(this.controller);
        Object res = this.method.invoke(controllerInstance, parameters);
        response.getWriter().println(res.toString());
        return true;
    }
}
